<template>
  <view class="content">
    <image class="logo" src="/static/logo.png" />
    <view class="text-area">
      <text class="title">{{ title }}</text>
    </view>
    <canvas class="webgl" type="webgl" id="gl" @touchstart="onTX" @touchmove="onTX" @touchend="onTX"></canvas>
  </view>
</template>

<script setup lang="ts">
import { onLoad, onReady, onUnload } from '@dcloudio/uni-app'
import { reactive, ref } from 'vue'

import { $cancelAnimationFrame, $requestAnimationFrame, $window, AmbientLight, DirectionalLight, PerspectiveCamera, PLATFORM, Scene, sRGBEncoding, WebGL1Renderer } from 'three-platformize'
import { WechatPlatform } from 'three-platformize/src/WechatPlatform'
import { GLTF, GLTFLoader } from 'three-platformize/examples/jsm/loaders/GLTFLoader'
import { OrbitControls } from 'three-platformize/examples/jsm/controls/OrbitControls'

const title = ref('Hello')

let disposing = false
let platform = null as unknown as WechatPlatform
let frameId = -1

onLoad(option => {
  console.log('onLoad', title)
})

onReady(() => {
  uni.createSelectorQuery().select('#gl').node(v => v).exec((res) => {
    const canvas = res[0].node

    platform = new WechatPlatform(canvas)
    PLATFORM.set(platform);

    const renderer = new WebGL1Renderer({ canvas, antialias: true, alpha: true })
    const camera = new PerspectiveCamera(75, canvas.width / canvas.height, 0.1, 1000);
    const scene = new Scene()
    const gltfLoader = new GLTFLoader()
    const controls = new OrbitControls(camera, canvas);
    controls.enableDamping = true

    gltfLoader.loadAsync('https://dtmall-tel.alicdn.com/edgeComputingConfig/upload_models/1591673169101/RobotExpressive.glb').then((gltf: GLTF) => {
      // @ts-ignore
      gltf.parser = null;
      gltf.scene.position.y = -2;
      scene.add(gltf.scene);
    })

    camera.position.z = 10
    renderer.outputEncoding = sRGBEncoding
    scene.add(new AmbientLight(0xffffff, 1.0))
    scene.add(new DirectionalLight(0xffffff, 1.0))
    renderer.setSize(canvas.width, canvas.height)
    renderer.setPixelRatio($window.devicePixelRatio)

    const render = () => {
      if (!disposing) frameId = $requestAnimationFrame(render)
      controls.update()
      renderer.render(scene, camera);
    }
    render()
  })
})

onUnload(() => {
  disposing = true
  $cancelAnimationFrame(frameId)
  PLATFORM.dispose()
})

const onTX = (e: any) => {
  platform.dispatchTouchEvent(e)
}

</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}
</style>
